<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Service\OpenShop\Feishu\SendSmsService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\AppPush\PushParam;
use Kuafu\AppPush\Push;

class NoticePay extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:notice-pay';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送时间：每天上午11点。发送逻辑：根据门店，只要有未支付的设计、设备、软装订单就向加盟商每天定时催付提醒，如果涉及同一个订单类型有多张订单，也只发送一条。';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private static $sendLists = [];

    public function handle()
    {
        if (config('app.env') != 'prod') {
            dd('非生产环境不跑');
        }

        // 筛选数据，准备数据
        OpenShopSiteMissionModel::query()
                                ->whereIn('stepStatus', [
                                    MissionTemplateEnum::STEP_STATUS_14,
                                    MissionTemplateEnum::STEP_STATUS_16,
                                    MissionTemplateEnum::STEP_STATUS_17
                                ])
                                ->where('status', SiteMissionEnum::STATUS_1)
                                ->where('expiredAt', '>=', time())
                                ->get()
                                ->each(function ($item) {
                                    $orderNo    = $item->orderNo;
                                    $stepStatus = $item->stepStatus;
                                    $uid        = $item->openShopSignOrderRel->merchantUserId;

                                    $key = $item->openShopSignOrderRel->merchantUserId . ':' . $stepStatus;
                                    if (isset(self::$sendLists[$key])) {
                                        return;
                                    }

                                    self::$sendLists[$key] = [
                                        'orderNo'    => $orderNo,
                                        'stepStatus' => $stepStatus,
                                        'uid'        => $uid,
                                        'name'       => $item->openShopUserIdentityCardRel->name,
                                        'kfShopCode' => $item->openShopSignOrderRel->kfShopCode,
                                    ];
                                });

        // 循环发送
        collect(self::$sendLists)->each(function ($item) {
            $orderNo    = $item['orderNo'];
            $stepStatus = $item['stepStatus'];
            $uid        = $item['uid'];
            $name       = $item['name'];
            $kfShopCode = $item['kfShopCode'];

            if ($stepStatus == MissionTemplateEnum::STEP_STATUS_14) {
                $smsTemplate = config('sms.template.designNoticePay');
                $appTemplate = config('appPush.template.designNoticePay');
            } elseif ($stepStatus == MissionTemplateEnum::STEP_STATUS_16) {
                $smsTemplate = config('sms.template.equipmentNoticePay');
                $appTemplate = config('appPush.template.equipmentNoticePay');
            } elseif ($stepStatus == MissionTemplateEnum::STEP_STATUS_17) {
                $smsTemplate = config('sms.template.decorateNoticePay');
                $appTemplate = config('appPush.template.decorateNoticePay');
            } else {
                return;
            }

            try {
                // 短信推送
                (new SendSmsService($orderNo))->noticePay($smsTemplate);

                // APP推送
                $message   = sprintf($appTemplate, $name, $kfShopCode);
                $pushParam = (new PushParam())
                    ->setMessage($message)
                    ->setUserIds([$uid]);

                (new Push($pushParam))->doPush();
            } catch (\Exception $e) {
                Log::warning("NoticePay push err: {$e->getMessage()}");
            }
        });
    }
}
